<script setup>
import { onMounted, reactive, ref } from "vue";
import axios from "../utils/http";
import { pickerOptionsDs } from "../utils/index";
import appTable from "../components/table/table.vue";
import PageContainer from "../components/PageContainer.vue";
import { ElMessageBox, ElMessage } from "element-plus";
import dayjs from "dayjs";
import DialogFound from "../components/DialogFound.vue";
import { useUserStore } from "../store/user";
const userStore = useUserStore();
const user = userStore.user;
const dialogVisible = ref(false);
const editlData = ref({});
const allData = ref([]);
const queryForm = ref();
let queryParams = ref({
  times: [
    dayjs().subtract(6, "day").startOf("day").format("YYYY-MM-DD HH:mm:ss"),
    dayjs().endOf("day").format("YYYY-MM-DD HH:mm:ss"),
  ],
  start: dayjs()
    .subtract(6, "day")
    .startOf("day")
    .format("YYYY-MM-DD HH:mm:ss"),
  end: dayjs().endOf("day").format("YYYY-MM-DD HH:mm:ss"),
});
const filterContent = ref([
  {
    el: {
      type: "datetimerange",
      startPlaceholder: "开始日期",
      endPlaceholder: "结束日期",
      valueFormat: "YYYY-MM-DD HH:mm:ss",
      defaultTime: [new Date(0, 0, 0, 12, 0, 0), new Date(0, 0, 0, 23, 59, 59)],
      disabledDate: pickerOptionsDs.disabledDate,
      shortcuts: pickerOptionsDs.shortcuts,
    },
    attrs: {
      class: "date-range",
    },
    label: "班结时间：",
    type: "date-picker",
    id: "times",
    outputFormat: (val) => {
      if (!val) {
        return { start: "", end: "" };
      }
      return {
        start: val[0],
        end: val[1],
      };
    },
  },
]);
// 新增
const onAddChannel = () => {
  // 清空数据（避免再次覆盖子组件）
  editlData.value = {};
  dialogVisible.value = true;
};
// 编辑
const onEditChannel = (row) => {
  editlData.value = row;
  dialogVisible.value = true;
};

// 表格
let tableContent = reactive({
  total: 0,
  list: [],
  otherHeight: 150,
  columns: [
    {
      prop: "date",
      label: "创建时间",
      align: "center",
      width: 200,
      formatter: (row, column) => {
        return dayjs(row.date).format("YYYY-MM-DD HH:mm:ss");
      },
    },
    {
      prop: "type",
      label: "收支类型",
      align: "center",
      el: {
        "show-overflow-tooltip": true,
      },
    },
    {
      prop: "describe",
      label: "收支描述",
      align: "center",
      el: {
        "show-overflow-tooltip": true,
      },
    },
    {
      prop: "income",
      label: "收入",
      align: "center",
      width: 170,
      formatter: (row, column, cellValue) => {
        return `<span style="color: #00d053">${row.income}</span>`;
      },
    },
    {
      prop: "expend",
      label: "支出",
      align: "center",
      width: 170,
      formatter: (row, column, cellValue) => {
        return `<span style="color: #f56767">${row.expend}</span>`;
      },
    },
    {
      prop: "cash",
      label: "账户现金",
      align: "center",
      width: 170,
      formatter: (row, column, cellValue) => {
        return `<span style="color: #4db3ff">${row.cash}</span>`;
      },
    },

    {
      prop: "remark",
      label: "备注",
      align: "center",
      el: {
        "show-overflow-tooltip": true,
      },
    },
  ], // 需要展示的列
  options: {
    stripe: true, // 是否为斑马纹 table
    loading: false, // 是否添加表格loading加载动画
    highlightCurrentRow: true, // 是否支持当前行高亮显示
    mutiSelect: false, // 是否支持列表项选中功能
    border: true, //是否显示边框
    numbers: true, //是否显示序号
  }, // table 的参数
  pagination: {
    pageNo: 1,
    pageSize: 5,
  }, // 分页参数
  operates: {
    width: 200,
    list: [
      {
        label: "编辑",
        type: "primary",
        plain: true,
        icon: "Edit",
        show: () => {
          return user.identity == "manager";
        },
        method: (index, row) => {
          console.log("编辑");
          onEditChannel(row);
        },
      },
      {
        label: "删除",
        type: "danger",
        icon: "Delete",
        plain: true,
        method: (index, row) => {
          console.log("删除");
          onDelChannel(row);
        },
        show: () => {
          return user.identity == "manager";
        },
      },
    ],
  },
});
// 切换每页显示的数量
const handleSizeChange = (pagination) => {
  tableContent.pagination = pagination;
  console.log("切换每页显示的数量", pagination);
  renderTable();
};
// 切换页码
const handleIndexChange = (pagination) => {
  tableContent.pagination = pagination;
  console.log("切换页码", pagination);
  renderTable();
};
//删除
const onDelChannel = async (row) => {
  await ElMessageBox.confirm("你确认删除该流水信息吗？", "温馨提示", {
    type: "warning",
    confirmButtonText: "确认",
    cancelButtonText: "取消",
  });
  await axios.delete(`/api/profile/delete/${row._id}`);
  ElMessage({ type: "success", message: "删除成功" });
  getProfile();
};
// 初始化
onMounted(() => {
  getProfile();
});

const getProfile = async () => {
  tableContent.options.loading = true;
  try {
    let { code, data } = await axios.get("/api/profile/list");
    console.log(code);
    if (code == 200) {
      allData.value = data.list;

      renderTable();
    }
  } catch (error) {
    console.log(error);
  } finally {
    tableContent.options.loading = false;
  }
};
/**
 * 前端分页函数
 */
const renderTable = () => {
  let { start, end } = queryForm.value.getFormValue();
  let { pageNo, pageSize } = tableContent.pagination;
  // 过滤数据
  let filteredData = allData.value.filter((item) => {
    let itemTime = dayjs(item.date);
    // 开始时间之后，结束时间之前 查询的时间范围
    return itemTime.isAfter(start) && itemTime.isBefore(end);
  });

  // 计算开始索引，即前一页的最后一个元素的索引
  let startLen = (pageNo - 1) * pageSize;

  // 计算结束索引，即当前页最后一个元素的索引
  let endLen = startLen + pageSize;
  console.log(startLen, endLen);

  // 截取当前页的数据
  tableContent.list = filteredData.slice(startLen, endLen);
  tableContent.total = filteredData.length;
};
// 搜索
const handleQuery = () => {
  tableContent.pagination = {
    pageNo: 1,
    pageSize: 5,
  };
  getProfile();
};
// 重置
const resetQuery = () => {
  queryParams.value = {
    times: [
      dayjs().subtract(6, "day").startOf("day").format("YYYY-MM-DD HH:mm:ss"),
      dayjs().endOf("day").format("YYYY-MM-DD HH:mm:ss"),
    ],
    start: dayjs()
      .subtract(6, "day")
      .startOf("day")
      .format("YYYY-MM-DD HH:mm:ss"),
    end: dayjs().endOf("day").format("YYYY-MM-DD HH:mm:ss"),
  };
  getProfile();
};
</script>
<template>
  <div class="app-container">
    <!-- submit.native.prevent 阻止表单默认提交 -->
    <el-form-renderer
      v-model:FormData="queryParams"
      :content="filterContent"
      ref="queryForm"
      class="render-form"
      @submit.native.prevent
      @keyup.enter.native="handleQuery"
    >
      <el-form-item>
        <el-button type="primary" @click="handleQuery">搜索</el-button>
        <el-button @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form-renderer>
    <page-container title="资金流水">
      <template #extra>
        <el-button type="primary" @click="onAddChannel"> 添加分类 </el-button>
      </template>

      <appTable
        :list="tableContent.list"
        :total="tableContent.total"
        :otherHeight="tableContent.otherHeight"
        :options="tableContent.options"
        :pagination="tableContent.pagination"
        :columns="tableContent.columns"
        :operates="tableContent.operates"
        @handleSizeChange="handleSizeChange"
        @handleIndexChange="handleIndexChange"
      >
      </appTable>
    </page-container>
    <DialogFound
      v-model:dialogVisible="dialogVisible"
      key="openDivideAccounts"
      :editlData="editlData"
      @success="getProfile"
    ></DialogFound>
  </div>
</template>

<style lang="scss" scoped></style>
